#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import urllib.parse
import requests
import loguru

logger = loguru.logger


class Emobile:
    def __init__(
        self,
        base_url,
        loginid,
        password,
        udid,
        clientos,
        clientosver,
        clienttype,
        logger=logger,
    ):
        self.logger = logger
        self.base_url = base_url
        self.client_url = urllib.parse.urljoin(base_url, "client.do")
        self.session = requests.Session()
        self.headers = {
            "Accept-Language": "en-GB,zh;q=0.5",
            "Accept-Charset": "utf-8;q=0.7,*;q=0.7",
            "Accept-Encoding": "gzip",
            "Timezone": "GMT+08:00",
            "Content-Type": "application/x-www-form-urlencoded",
            "User-Agent": "E-Mobile/6.5.46 (Linux;U;Android 2.2.1;zh-CN;Nexus One Build.FRG83) AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1",
        }
        self.do_checkin_result = None
        self.do_checkout_result = None
        self.loginid = loginid
        self.password = password
        self.udid = udid
        self.clientos = clientos
        self.clientosver = clientosver
        self.clienttype = clienttype

    def get_config(self):
        get_config_data = dict(clientver="6.5.46", clienttype=self.clienttype, androidShowEScene="1")
        try:
            get_config_resp = self.session.post(
                self.client_url, headers=self.headers, params=dict(method="getconfig"), data=get_config_data, timeout=10
            )
            self.get_config_result = get_config_resp.json()
            self.logger.info("get_config for version {}".format(self.get_config_result["config"]["version"]))
        except requests.RequestException as e:
            self.logger.error("get_config requests Exception {}".format(repr(e)))
        except Exception:
            self.logger.exception("get_config exception")

    def login(self):
        self.headers["Cookie2"] = "$Version=1"
        login_data = dict(
            method="login",
            loginid=self.loginid,
            password=self.password,
            isneedmoulds="1",
            client="1",
            clientver="6.5.46",
            udid=self.udid,
            token="",
            clientos=self.clientos,
            clientosver=self.clientosver,
            clienttype=self.clienttype,
            language="en",
            country="GB",
            authcode="",
            dynapass="",
            tokenpass="",
            relogin="1",
            clientuserid="",
        )
        try:
            login_resp = self.session.post(self.client_url, headers=self.headers, data=login_data, timeout=10)
            self.login_result = login_resp.json()
            self.logger.info("login result sesison key {}".format(self.login_result["sessionkey"]))
        except requests.RequestException as e:
            self.logger.error("login requests exception {}".format(repr(e)))
        except Exception:
            self.logger.exception("login exception")

    def get_user(self):
        try:
            get_user_resp = self.session.get(
                self.client_url, headers=self.headers, params=dict(method="getuser"), timeout=10
            )
            self.get_user_result = get_user_resp.json()
            self.logger.info("get_user id {}".format(self.get_user_result["id"]))
        except requests.RequestException as e:
            self.logger.error("get_user requests exception {}".format(repr(e)))
        except Exception:
            self.logger.exception("get_user exception")

    def get_checkin_status(self):
        try:
            get_checkin_status_params = dict(method="checkin", type="getStatus")
            get_checkin_status_resp = self.session.get(
                self.client_url, headers=self.headers, params=get_checkin_status_params, timeout=10
            )
            self.get_checkin_status_result = get_checkin_status_resp.json()
            btns = self.get_checkin_status_result["signbtns"]
            self.logger.info("checkin status {}".format(btns[0]))
            self.logger.info("checkout status {}".format(btns[1]))
        except requests.RequestException as e:
            self.logger.error("get_checkin_status requests exception {}".format(repr(e)))
        except Exception:
            self.logger.exception("get_checkin_status exception")

    def get_checkin(self):
        try:
            get_checkin_params = dict(method="checkin")
            get_checkin_resp = self.session.get(
                self.client_url, headers=self.headers, params=get_checkin_params, timeout=10
            )
            self.get_checkin_result = get_checkin_resp.json()
            self.logger.info("checkin enbable status {}".format(self.get_checkin_result))
        except requests.RequestException as e:
            self.logger.error("get_checkin requests exception {}".format(repr(e)))
        except Exception:
            self.logger.exception("get_checkin exception")

    def do_checkin(self):
        try:
            checkin_params = dict(
                method="checkin",
                type="checkin",
                latlng="23.130927,113.544289",
                addr="Guangdong+Guangzhou+Huangpu+Hengda+Road+No.1+Near+Guangzhou+Zhiguang+Electric+Co.%2C+Ltd.",
                sessionkey=self.session.cookies.get("JSESSIONID"),
                wifiMac="null",
            )
            checkin_resp = self.session.get(self.client_url, headers=self.headers, params=checkin_params, timeout=10)
            self.do_checkin_result = checkin_resp.json()
            self.logger.info("checkin result {}".format(self.do_checkin_result))
        except requests.RequestException as e:
            self.logger.error("get_checkin requests exception {}".format(repr(e)))
        except Exception:
            self.logger.exception("get_checkin exception")

    def do_checkout(self):
        try:
            checkout_params = dict(
                method="checkin",
                type="checkout",
                latlng="23.129467,113.545916",
                addr="Guangdong+Guangzhou+Huangpu+Punan+Road+No.30+Near+Blue+Moon+Scientific+Research+Office+Building",
                sessionkey=self.session.cookies.get("JSESSIONID"),
                wifiMac="null",
            )
            checkout_resp = self.session.get(self.client_url, headers=self.headers, params=checkout_params, timeout=10)
            self.do_checkout_result = checkout_resp.json()
            self.logger.info("checkout result {}".format(self.do_checkout_result))
        except requests.RequestException as e:
            self.logger.error("do_checkout requests exception {}".format(repr(e)))
        except Exception:
            self.logger.exception("do_checkout exception")
